package com.example.owner.lettery1.ui;


import android.app.Service;
import android.content.Intent;
import android.os.Environment;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.support.v4.content.LocalBroadcastManager;
import android.util.Log;


import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

import static android.support.constraint.Constraints.TAG;


public class DownloadIntentService extends Service {

    @Override
    public int onStartCommand(@Nullable Intent intent, int flags, int startId) {
        onCreateDownload(intent.getStringExtra(MainActivity.DOWNLOAD_KEY));
        return super.onStartCommand(intent, flags, startId);
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }


    private void onCreateDownload(String downloadUrl) {
        OkHttpClient okHttp = new OkHttpClient();
        Request request = new Request.Builder().url(downloadUrl).build();
        okHttp.newCall(request).enqueue(new okhttp3.Callback() {
            @Override
            public void onFailure(okhttp3.Call call, IOException e) {
                e.printStackTrace();
                stopSelf();
            }

            @Override
            public void onResponse(okhttp3.Call call, Response response) throws IOException {
                InputStream inputStream = response.body().byteStream();
                long contentLength = response.body().contentLength();

                FileOutputStream fileOutputStream = null;
                Log.d(TAG, "onResponse: =======开始下载");
                try {
                    File file = new File(Environment.getExternalStorageDirectory(), "bocai.apk");
                    fileOutputStream = new FileOutputStream(file);
                    byte[] buffer = new byte[2048];
                    int len = 0;
                    long progress = 0;
                    int total = 0;
                    while ((len = inputStream.read(buffer)) != -1) {
                        fileOutputStream.write(buffer, 0, len);
                        total += len;
                    }
                    fileOutputStream.flush();
                    Intent intent = new Intent(MainActivity.DOWNLOAD_KEY);
                    intent.putExtra(MainActivity.FILE_KEY, file.getAbsolutePath());
                    LocalBroadcastManager.getInstance(DownloadIntentService.this).sendBroadcast(intent);
                    Log.d(TAG, "onResponse:  ===========跳转广播");
                } catch (IOException e) {
                    e.printStackTrace();
                }
                stopSelf();
            }
        });
    }


}
